<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册 - 智能营养管理系统</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px 0;
        }
        .register-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
        }
        .register-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px 20px 0 0;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 10px;
            background-color: #e9ecef;
            color: #6c757d;
            font-weight: bold;
        }
        .step.active {
            background-color: #007bff;
            color: white;
        }
        .step.completed {
            background-color: #28a745;
            color: white;
        }
        .step-line {
            width: 50px;
            height: 2px;
            background-color: #e9ecef;
            margin-top: 19px;
        }
        .step-line.completed {
            background-color: #28a745;
        }
        .form-section {
            display: none;
        }
        .form-section.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-7">
                <div class="card register-card border-0">
                    <div class="card-header register-header text-center py-4">
                        <h3 class="mb-0">
                            <i class="fas fa-user-plus me-2"></i>
                            创建账户
                        </h3>
                        <p class="mb-0 mt-2">开始您的智能营养管理之旅</p>
                    </div>
                    
                    <div class="card-body p-5">
                        <!-- 步骤指示器 -->
                        <div class="step-indicator">
                            <div class="step active" id="step1">1</div>
                            <div class="step-line" id="line1"></div>
                            <div class="step" id="step2">2</div>
                            <div class="step-line" id="line2"></div>
                            <div class="step" id="step3">3</div>
                        </div>
                        
                        <!-- 注册表单 -->
                        <form th:action="@{/register}" method="post" th:object="${userRegistration}" id="registrationForm">
                            <!-- 第一步：基本信息 -->
                            <div class="form-section active" id="section1">
                                <h5 class="mb-4 text-center">基本信息</h5>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="username" class="form-label">
                                            <i class="fas fa-user me-2"></i>用户名 *
                                        </label>
                                        <input type="text" class="form-control" 
                                               th:field="*{username}" id="username" 
                                               placeholder="3-50个字符，仅限字母数字下划线" required>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('username')}" 
                                             th:errors="*{username}"></div>
                                        <div class="form-text" id="usernameHelp"></div>
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="email" class="form-label">
                                            <i class="fas fa-envelope me-2"></i>邮箱 *
                                        </label>
                                        <input type="email" class="form-control" 
                                               th:field="*{email}" id="email" 
                                               placeholder="your@example.com" required>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('email')}" 
                                             th:errors="*{email}"></div>
                                        <div class="form-text" id="emailHelp"></div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="password" class="form-label">
                                            <i class="fas fa-lock me-2"></i>密码 *
                                        </label>
                                        <div class="input-group">
                                            <input type="password" class="form-control" 
                                                   th:field="*{password}" id="password" 
                                                   placeholder="至少6个字符" required>
                                            <button class="btn btn-outline-secondary" type="button" 
                                                    onclick="togglePassword('password', 'passwordIcon')">
                                                <i class="fas fa-eye" id="passwordIcon"></i>
                                            </button>
                                        </div>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('password')}" 
                                             th:errors="*{password}"></div>
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="confirmPassword" class="form-label">
                                            <i class="fas fa-lock me-2"></i>确认密码 *
                                        </label>
                                        <div class="input-group">
                                            <input type="password" class="form-control" 
                                                   th:field="*{confirmPassword}" id="confirmPassword" 
                                                   placeholder="再次输入密码" required>
                                            <button class="btn btn-outline-secondary" type="button" 
                                                    onclick="togglePassword('confirmPassword', 'confirmPasswordIcon')">
                                                <i class="fas fa-eye" id="confirmPasswordIcon"></i>
                                            </button>
                                        </div>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('confirmPassword')}" 
                                             th:errors="*{confirmPassword}"></div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="realName" class="form-label">
                                        <i class="fas fa-id-card me-2"></i>真实姓名
                                    </label>
                                    <input type="text" class="form-control" 
                                           th:field="*{realName}" id="realName" 
                                           placeholder="请输入您的真实姓名">
                                    <div class="invalid-feedback" th:if="${#fields.hasErrors('realName')}" 
                                         th:errors="*{realName}"></div>
                                </div>
                                
                                <div class="d-grid">
                                    <button type="button" class="btn btn-primary" onclick="nextStep(1)">
                                        下一步 <i class="fas fa-arrow-right ms-2"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- 第二步：身体信息 -->
                            <div class="form-section" id="section2">
                                <h5 class="mb-4 text-center">身体信息</h5>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="gender" class="form-label">
                                            <i class="fas fa-venus-mars me-2"></i>性别 *
                                        </label>
                                        <select class="form-select" th:field="*{gender}" id="gender" required>
                                            <option value="">请选择性别</option>
                                            <option value="MALE">男</option>
                                            <option value="FEMALE">女</option>
                                            <option value="OTHER">其他</option>
                                        </select>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('gender')}"
                                             th:errors="*{gender}"></div>
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="age" class="form-label">
                                            <i class="fas fa-birthday-cake me-2"></i>年龄 *
                                        </label>
                                        <input type="number" class="form-control"
                                               th:field="*{age}" id="age"
                                               placeholder="岁" min="1" max="150" required>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('age')}"
                                             th:errors="*{age}"></div>
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="activityLevel" class="form-label">
                                            <i class="fas fa-running me-2"></i>活动水平 *
                                        </label>
                                        <select class="form-select" th:field="*{activityLevel}" id="activityLevel" required>
                                            <option value="">请选择活动水平</option>
                                            <option value="SEDENTARY">久坐 (很少运动)</option>
                                            <option value="LIGHT">轻度活动 (每周1-3次)</option>
                                            <option value="MODERATE">中度活动 (每周3-5次)</option>
                                            <option value="ACTIVE">高度活动 (每周6-7次)</option>
                                            <option value="VERY_ACTIVE">极高活动 (每天2次)</option>
                                        </select>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('activityLevel')}"
                                             th:errors="*{activityLevel}"></div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="height" class="form-label">
                                            <i class="fas fa-ruler-vertical me-2"></i>身高 *
                                        </label>
                                        <div class="input-group">
                                            <input type="number" class="form-control"
                                                   th:field="*{height}" id="height"
                                                   placeholder="170" min="50" max="300" step="0.1" required>
                                            <span class="input-group-text">cm</span>
                                        </div>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('height')}"
                                             th:errors="*{height}"></div>
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label for="weight" class="form-label">
                                            <i class="fas fa-weight me-2"></i>体重 *
                                        </label>
                                        <div class="input-group">
                                            <input type="number" class="form-control"
                                                   th:field="*{weight}" id="weight"
                                                   placeholder="65" min="20" max="1000" step="0.1" required>
                                            <span class="input-group-text">kg</span>
                                        </div>
                                        <div class="invalid-feedback" th:if="${#fields.hasErrors('weight')}"
                                             th:errors="*{weight}"></div>
                                    </div>
                                </div>

                                <!-- BMI 计算显示 -->
                                <div class="alert alert-info" id="bmiInfo" style="display: none;">
                                    <h6><i class="fas fa-calculator me-2"></i>BMI 计算结果</h6>
                                    <p class="mb-0">您的BMI为：<span id="bmiValue"></span> - <span id="bmiStatus"></span></p>
                                </div>

                                <div class="row">
                                    <div class="col-6">
                                        <button type="button" class="btn btn-outline-secondary w-100" onclick="prevStep(2)">
                                            <i class="fas fa-arrow-left me-2"></i>上一步
                                        </button>
                                    </div>
                                    <div class="col-6">
                                        <button type="button" class="btn btn-primary w-100" onclick="nextStep(2)">
                                            下一步 <i class="fas fa-arrow-right ms-2"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- 第三步：营养目标和偏好 -->
                            <div class="form-section" id="section3">
                                <h5 class="mb-4 text-center">营养目标设定</h5>

                                <div class="alert alert-info">
                                    <h6><i class="fas fa-lightbulb me-2"></i>智能推荐</h6>
                                    <p class="mb-0">系统将根据您的身体信息自动计算推荐的营养目标，您也可以手动调整。</p>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="dailyCaloriesGoal" class="form-label">
                                            <i class="fas fa-fire me-2"></i>每日卡路里目标
                                        </label>
                                        <div class="input-group">
                                            <input type="number" class="form-control"
                                                   th:field="*{dailyCaloriesGoal}" id="dailyCaloriesGoal"
                                                   placeholder="2000" min="800" max="5000">
                                            <span class="input-group-text">kcal</span>
                                        </div>
                                        <div class="form-text">推荐值：<span id="recommendedCalories">计算中...</span></div>
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label for="dailyProteinGoal" class="form-label">
                                            <i class="fas fa-drumstick-bite me-2"></i>每日蛋白质目标
                                        </label>
                                        <div class="input-group">
                                            <input type="number" class="form-control"
                                                   th:field="*{dailyProteinGoal}" id="dailyProteinGoal"
                                                   placeholder="150" min="30" max="500">
                                            <span class="input-group-text">g</span>
                                        </div>
                                        <div class="form-text">推荐值：<span id="recommendedProtein">计算中...</span></div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="dailyCarbsGoal" class="form-label">
                                            <i class="fas fa-bread-slice me-2"></i>每日碳水化合物目标
                                        </label>
                                        <div class="input-group">
                                            <input type="number" class="form-control"
                                                   th:field="*{dailyCarbsGoal}" id="dailyCarbsGoal"
                                                   placeholder="250" min="50" max="800">
                                            <span class="input-group-text">g</span>
                                        </div>
                                        <div class="form-text">推荐值：<span id="recommendedCarbs">计算中...</span></div>
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label for="dailyFatGoal" class="form-label">
                                            <i class="fas fa-tint me-2"></i>每日脂肪目标
                                        </label>
                                        <div class="input-group">
                                            <input type="number" class="form-control"
                                                   th:field="*{dailyFatGoal}" id="dailyFatGoal"
                                                   placeholder="65" min="20" max="200">
                                            <span class="input-group-text">g</span>
                                        </div>
                                        <div class="form-text">推荐值：<span id="recommendedFat">计算中...</span></div>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <button type="button" class="btn btn-outline-info w-100" onclick="calculateRecommendedGoals()">
                                        <i class="fas fa-calculator me-2"></i>使用推荐值
                                    </button>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="dietaryRestrictions" class="form-label">
                                            <i class="fas fa-ban me-2"></i>饮食限制
                                        </label>
                                        <textarea class="form-control" th:field="*{dietaryRestrictions}"
                                                  id="dietaryRestrictions" rows="2"
                                                  placeholder="如：素食、低脂、低盐等"></textarea>
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label for="allergies" class="form-label">
                                            <i class="fas fa-exclamation-triangle me-2"></i>过敏信息
                                        </label>
                                        <textarea class="form-control" th:field="*{allergies}"
                                                  id="allergies" rows="2"
                                                  placeholder="如：花生、海鲜、乳制品等"></textarea>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-6">
                                        <button type="button" class="btn btn-outline-secondary w-100" onclick="prevStep(3)">
                                            <i class="fas fa-arrow-left me-2"></i>上一步
                                        </button>
                                    </div>
                                    <div class="col-6">
                                        <button type="submit" class="btn btn-success w-100">
                                            <i class="fas fa-check me-2"></i>完成注册
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <hr class="my-4">

                        <div class="text-center">
                            <p class="mb-0">已有账户？
                                <a th:href="@{/login}" class="text-decoration-none">
                                    立即登录
                                </a>
                            </p>
                        </div>
                    </div>
                </div>

                <div class="text-center mt-4">
                    <a th:href="@{/}" class="text-white text-decoration-none">
                        <i class="fas fa-arrow-left me-2"></i>返回首页
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        let currentStep = 1;

        function nextStep(step) {
            if (validateStep(step)) {
                currentStep = step + 1;
                showStep(currentStep);
                updateStepIndicator();

                if (step === 2) {
                    calculateBMI();
                    calculateRecommendedGoals();
                }
            }
        }

        function prevStep(step) {
            currentStep = step - 1;
            showStep(currentStep);
            updateStepIndicator();
        }

        function showStep(step) {
            document.querySelectorAll('.form-section').forEach(section => {
                section.classList.remove('active');
            });
            document.getElementById('section' + step).classList.add('active');
        }

        function updateStepIndicator() {
            for (let i = 1; i <= 3; i++) {
                const stepElement = document.getElementById('step' + i);
                const lineElement = document.getElementById('line' + i);

                if (i < currentStep) {
                    stepElement.classList.add('completed');
                    stepElement.classList.remove('active');
                    if (lineElement) lineElement.classList.add('completed');
                } else if (i === currentStep) {
                    stepElement.classList.add('active');
                    stepElement.classList.remove('completed');
                } else {
                    stepElement.classList.remove('active', 'completed');
                    if (lineElement) lineElement.classList.remove('completed');
                }
            }
        }

        function validateStep(step) {
            const section = document.getElementById('section' + step);
            const requiredFields = section.querySelectorAll('[required]');
            let isValid = true;

            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });

            if (step === 1) {
                // 验证密码匹配
                const password = document.getElementById('password').value;
                const confirmPassword = document.getElementById('confirmPassword').value;
                if (password !== confirmPassword) {
                    document.getElementById('confirmPassword').classList.add('is-invalid');
                    isValid = false;
                }
            }

            return isValid;
        }

        function togglePassword(fieldId, iconId) {
            const field = document.getElementById(fieldId);
            const icon = document.getElementById(iconId);

            if (field.type === 'password') {
                field.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                field.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        function calculateBMI() {
            const height = parseFloat(document.getElementById('height').value);
            const weight = parseFloat(document.getElementById('weight').value);

            if (height && weight) {
                const heightInMeters = height / 100;
                const bmi = weight / (heightInMeters * heightInMeters);

                document.getElementById('bmiValue').textContent = bmi.toFixed(1);

                let status;
                if (bmi < 18.5) status = '偏瘦';
                else if (bmi < 24) status = '正常';
                else if (bmi < 28) status = '超重';
                else status = '肥胖';

                document.getElementById('bmiStatus').textContent = status;
                document.getElementById('bmiInfo').style.display = 'block';
            }
        }

        function calculateRecommendedGoals() {
            const height = parseFloat(document.getElementById('height').value);
            const weight = parseFloat(document.getElementById('weight').value);
            const age = parseInt(document.getElementById('age').value);
            const gender = document.getElementById('gender').value;
            const activityLevel = document.getElementById('activityLevel').value;

            if (height && weight && age && gender && activityLevel) {
                // 计算BMR
                let bmr;
                if (gender === 'MALE') {
                    bmr = 10 * weight + 6.25 * height - 5 * age + 5;
                } else {
                    bmr = 10 * weight + 6.25 * height - 5 * age - 161;
                }

                // 活动系数
                const activityMultipliers = {
                    'SEDENTARY': 1.2,
                    'LIGHT': 1.375,
                    'MODERATE': 1.55,
                    'ACTIVE': 1.725,
                    'VERY_ACTIVE': 1.9
                };

                const tdee = bmr * activityMultipliers[activityLevel];
                const protein = weight * 1.6;
                const fat = tdee * 0.275 / 9;
                const carbs = (tdee - protein * 4 - fat * 9) / 4;

                document.getElementById('recommendedCalories').textContent = Math.round(tdee) + ' kcal';
                document.getElementById('recommendedProtein').textContent = Math.round(protein) + ' g';
                document.getElementById('recommendedCarbs').textContent = Math.round(carbs) + ' g';
                document.getElementById('recommendedFat').textContent = Math.round(fat) + ' g';
            }
        }

        function useRecommendedGoals() {
            const recommendedCalories = document.getElementById('recommendedCalories').textContent.match(/\d+/);
            const recommendedProtein = document.getElementById('recommendedProtein').textContent.match(/\d+/);
            const recommendedCarbs = document.getElementById('recommendedCarbs').textContent.match(/\d+/);
            const recommendedFat = document.getElementById('recommendedFat').textContent.match(/\d+/);

            if (recommendedCalories) document.getElementById('dailyCaloriesGoal').value = recommendedCalories[0];
            if (recommendedProtein) document.getElementById('dailyProteinGoal').value = recommendedProtein[0];
            if (recommendedCarbs) document.getElementById('dailyCarbsGoal').value = recommendedCarbs[0];
            if (recommendedFat) document.getElementById('dailyFatGoal').value = recommendedFat[0];
        }

        // 实时验证用户名和邮箱
        document.getElementById('username').addEventListener('blur', function() {
            const username = this.value;
            if (username.length >= 3) {
                fetch('/api/users/check-username?username=' + encodeURIComponent(username))
                    .then(response => response.json())
                    .then(data => {
                        const helpText = document.getElementById('usernameHelp');
                        if (data.available) {
                            helpText.textContent = '✓ 用户名可用';
                            helpText.className = 'form-text text-success';
                        } else {
                            helpText.textContent = '✗ 用户名已被使用';
                            helpText.className = 'form-text text-danger';
                        }
                    });
            }
        });

        document.getElementById('email').addEventListener('blur', function() {
            const email = this.value;
            if (email.includes('@')) {
                fetch('/api/users/check-email?email=' + encodeURIComponent(email))
                    .then(response => response.json())
                    .then(data => {
                        const helpText = document.getElementById('emailHelp');
                        if (data.available) {
                            helpText.textContent = '✓ 邮箱可用';
                            helpText.className = 'form-text text-success';
                        } else {
                            helpText.textContent = '✗ 邮箱已被注册';
                            helpText.className = 'form-text text-danger';
                        }
                    });
            }
        });

        // 身高体重变化时重新计算BMI
        document.getElementById('height').addEventListener('input', calculateBMI);
        document.getElementById('weight').addEventListener('input', calculateBMI);

        // 身体信息变化时重新计算推荐目标
        ['height', 'weight', 'age', 'gender', 'activityLevel'].forEach(id => {
            document.getElementById(id).addEventListener('change', calculateRecommendedGoals);
        });
    </script>
</body>
</html>
